<template>
  <div>
    <!--请假录入-->
    <Dialog
      ref="d1"
      dialogCls="mydlgg"
      headerCls="mydlgg-head"
      footerCls="mydlgg-foot"
      :dialogStyle="{ width: '550px', height: '450px', marginTop: '50px' }"
      :modal="true"
      borderType="thin"
      :draggable="true"
    >
      <div slot="header">
        <span class="headerIcon newlyAdded"></span>
        <span class="titleStyle">批量请假</span>
      </div>

      <div class="dlgContent">
        <div style="width: 100%; height: 100%; margin-left: 5px;">
          <!--          <div style="width:100%; height: 100%;" >-->
          <fieldset class="form-fieldset">
            <legend>
              <b class="fieldsetLegend">请假信息</b>
            </legend>
            <div class="form-item">
              <Label style="width: 55px">开始日期</Label>
              <DateBox
                inputId="lrStartDate"
                v-model="lr.dateBegin"
                format="yyyy-MM-dd"
                @selectionChange="selectionChange"
                :editable="false"
              ></DateBox>
            </div>
            <div class="form-item">
              <Label>结束日期</Label>
              <DateBox
                inputId="lrEndDate"
                v-model="lr.dateEnd"
                format="yyyy-MM-dd"
                @selectionChange="selectionChange"
                :editable="false"
              ></DateBox>
            </div>

            <div class="form-item">
              <Label style="width: 55px">开始时间</Label>
              <NumberBox
                :max="23"
                :min="0"
                v-model="lr.startTimeHour"
                :prefix="lr.startTimeHour < 10 ? '0' : ''"
                style="width: 25%"
              ></NumberBox>
              <span style="margin-left: 5px;">时</span>
              <NumberBox
                :max="59"
                :min="0"
                v-model="lr.startTimeMinute"
                :prefix="lr.startTimeMinute < 10 ? '0' : ''"
                style="width:25%; margin-left: 10px;"
              ></NumberBox>
              <span style="margin-left: 5px; ">分</span>
            </div>

            <div class="form-item">
              <Label style="width: 55px">结束时间</Label>
              <NumberBox
                :max="23"
                :min="0"
                v-model="lr.endTimeHour"
                :prefix="lr.endTimeHour < 10 ? '0' : ''"
                style="width: 25%"
              ></NumberBox>
              <span style="margin-left: 5px;">时</span>
              <NumberBox
                :max="59"
                :min="0"
                v-model="lr.endTimeMinute"
                :prefix="lr.endTimeMinute < 10 ? '0' : ''"
                style="width: 25%; margin-left: 10px;"
              ></NumberBox>
              <span style="margin-left: 5px;">分</span>
            </div>

            <div class="form-item">
              <Label style="width: 55px">假类</Label>
              <ComboGrid
                valueField="value"
                textField="text"
                :virtualScroll="true"
                :data="lr.leaveData"
                :rowHeight="lr.rowHeight"
                v-model="lr.requestData.leaveType"
              >
                <DataGrid slot="grid" :border="false" class="grid-border">
                  <GridColumn
                    field="value"
                    title="编号"
                    align="center"
                  ></GridColumn>
                  <GridColumn
                    field="text"
                    title="名称"
                    align="center"
                  ></GridColumn>
                </DataGrid>
              </ComboGrid>
            </div>

            <div class="form-item">
              <Label style="width: 55px">请假时长</Label>
              <NumberBox
                :max="23"
                :min="0"
                v-model="lr.hour"
                :prefix="lr.hour < 10 ? '0' : ''"
                style="width: 25%"
              ></NumberBox>
              <span style="margin-left: 5px;">时</span>
              <NumberBox
                :max="59"
                :min="0"
                v-model="lr.minute"
                :prefix="lr.minute < 10 ? '0' : ''"
                style="width: 25%; margin-left: 10px;"
              ></NumberBox>
              <span style="margin-left: 5px;">分</span>
            </div>
          </fieldset>

          <!--          <fieldset class="form-fieldset" >-->
          <!--            <legend>-->
          <!--              <b style="color:#293569">选择审批人</b>-->
          <!--            </legend>-->
          <!--            <select-approver-->
          <!--                    ref="appr"-->
          <!--                    v-show="lr.isShowAppr"-->
          <!--            ></select-approver>-->

          <!--            <div v-show="lr.isShowAppr == false">-->
          <!--              <p>该假类无需审批</p>-->
          <!--            </div>-->
          <!--          </fieldset>-->

          <fieldset class="form-fieldset" style="height: 100px;">
            <legend>
              <b style="color:red">*</b>
              <b style="color:#293569">请假事由</b>
            </legend>
            <!-- fieldset、legend如果需要带边框加标题的容器这俩标签必须保留 -->
            <TextBox
              :multiline="true"
              v-model="lr.requestData.remark"
              style="width:100%; height: 83%;"
              placeholder="请填写请假请假事由（必填）"
            ></TextBox>
          </fieldset>

          <fieldset class="form-fieldset" style="height: 100px;">
            <legend>
              <b style="color:#293569">上传附件</b>
            </legend>
            <upload-file ref="upload1" class="uploadFile" />
            <upload-file ref="upload2" class="uploadFile" />
            <upload-file ref="upload3" class="uploadFile" />
          </fieldset>
        </div>
      </div>

      <div slot="footer" class="dlg-foot">
        <!--        <div class="dlgFoot1">-->
        <!-- footer、footerDiv这两个div必须保留 -->
        <LinkButton @click="saveLeave" class="saveBtn">保存</LinkButton>
        <LinkButton @click="closeaddLeave" class="cancelBtn">返回</LinkButton>
        <!--        </div>-->
      </div>
    </Dialog>

    <!--请假错误详情-->
    <Dialog
      ref="errorXq"
      dialogCls="mydlgg"
      headerCls="mydlgg-head"
      footerCls="mydlgg-foot"
      :dialogStyle="{ width: '720px' }"
      :modal="true"
      borderType="thin"
    >
      <div slot="header">
        <span class="headerIcon newlyAdded"></span>
        <span class="titleStyle">请假错误详情</span>
      </div>
      <div class="insidePadding">
        <!-- 这个div必须保留 -->
        <fieldset class="fieldsetStyle">
          <!-- 表格容器   -->
          <div style="height: 450px">
            <ag-grid-vue
              style="width: 100%; height: 100%;"
              class="ag-theme-balham"
              :rowData="lr.err.xqRowData"
              :columnDefs="lr.err.xqColumnDefs"
            ></ag-grid-vue>
          </div>
        </fieldset>
      </div>
    </Dialog>
  </div>
</template>

<script>
import sidebarDept from "@/components/dept/sidebarDept";
import { tableBoxHeight } from "@/api/communal";
import leave from "@/api/leave/leave";
import BdGrid from "@/components/gridNoPage";
import { AgGridVue } from "ag-grid-vue";
import dateUtil from "@/utils/dateUtils";
import user from "@/api/user";
import UploadFile from "@/components/uploadFile";
import selectApprover from "@/components/selectApprover";

export default {
  components: {
    sidebarDept,
    BdGrid,
    AgGridVue,
    UploadFile,
    selectApprover
  },
  name: "",
  data() {
    return {
      gridLeft: "leaveTree",
      /*详情界面表格*/
      xq: {
        xqRowData: [],
        xqColumnDefs: [
          { headerName: "工号", field: "userNo", width: 100 },
          { headerName: "姓名", field: "userLname", width: 100 },
          { headerName: "部门", field: "depName", width: 200 }
        ],
        orderId: "",
        leaveName: "",
        startDate: "",
        endDate: ""
      },
      /*录入界面数据*/
      lr: {
        //最小请假时间
        minMinute: 0,
        //最大请假时间
        maxMinute: 0,
        //步长
        increment: 1,
        pageTotalNum: 0,
        rowHeight: 30,
        peopleColumns: [],

        /*时间段*/
        startDate: "",
        endDate: "",
        /*假类*/
        leaveData: [],
        dayColumns: [],
        //开始时间时
        startTimeHour: 0,
        //开始时间分
        startTimeMinute: 0,
        //结束时间时
        endTimeHour: 0,
        //结束时间分
        endTimeMinute: 0,
        /*时间*/
        minute: 0,
        hour: 0,
        /*是否显示审批下拉框*/
        isShowAppr: true,
        //请假开始日期
        dateBegin: new Date(),
        //请假结束日期
        dateEnd: new Date(),
        /*提交对象*/
        requestData: {
          //上传的文件名数组
          uploadFileNames: [],
          //选中的请假ID
          leaveType: "",
          //全部日期总时长
          totalDuration: 0,
          //请假原因
          remark: "",
          //每日请假详情（日期，假类，时间）
          leaveDateData: [],
          //请假开始日期
          startDate: "",
          //请假结束日期
          endDate: "",
          //请假开始时间
          startTime: "",
          //请假结束时间
          endTime: "",
          /*请假人员表格  选择的人员*/
          peopleData: [],
          /*上级审批人*/
          selectedApprover: [],
          /*确定的请假类型是否是额度假*/
          ishaveedu: 0,
          /*申请类型：个人/批量（个人申请/部门申请）1：个人，2：部门*/
          applyType: 2
        },
        err: {
          xqRowData: [],
          xqColumnDefs: [
            { headerName: "工号", field: "userNo", width: 100 },
            { headerName: "姓名", field: "userName", width: 100 },
            { headerName: "部门", field: "deptName", width: 200 },
            { headerName: "错误信息", field: "errorMsg", width: 240 }
          ]
        }
      },
      /*复选框*/
      allChecked: false,
      rowClicked: false
    };
  },
  props: {
    parentSearch: Function
  },
  mounted() {
    tableBoxHeight();
    this.$refs.d1.close();
    this.$refs.errorXq.close();
    this.getKtQingj();
  },
  computed: {
    checkedRows() {
      return this.lr.requestData.peopleData.filter(row => row.selected);
    }
  },
  methods: {
    //获取假类信息
    async getKtQingj() {
      let res = await leave.getLeaveType({
        applyType: 1
      });
      if (res.success) {
        for (let index in res.result) {
          let temp = {
            value: res.result[index].bh,
            text: res.result[index].mc,
            minsj:
              res.result[index].minsj != null ? res.result[index].minsj : 0,
            multiplesj:
              res.result[index].multiplesj != null
                ? res.result[index].multiplesj
                : 1,
            timelimit:
              res.result[index].timelimit != null
                ? res.result[index].timelimit
                : 0,
            ishaveedu:
              res.result[index].ishaveedu != null
                ? res.result[index].ishaveedu
                : 0
          };
          this.lr.leaveData.push(temp);
        }
      } else {
        this.$messager.alert({
          title: "异常错误",
          icon: "error",
          msg: "加载假类数据失败!"
        });
      }
    },
    //初始化录入界面数据
    initLrData() {
      //选择的人员列表初始化
      this.lr.requestData.peopleData = [];
      this.lr.pageTotalNum = 0;
      //日期初始化
      this.lr.requestData.startDate = new Date();
      this.lr.requestData.endDate = new Date();
      //假类初始化
      this.lr.requestData.leaveType = "";
      //开始时间  结束时间清除
      this.lr.startTimeHour = 0;
      this.lr.startTimeMinute = 0;
      this.lr.endTimeHour = 0;
      this.lr.endTimeMinute = 0;
      //时长
      this.lr.hour = 0;
      this.lr.minute = 0;
      //请加日详情表格初始化
      this.lr.requestData.totalDuration = 0;
      this.lr.requestData.leaveDateData = [];
      //请假原因初始化
      this.lr.requestData.remark = "";
      //附件初始化
      this.lr.requestData.uploadFileNames = [];
      this.lr.requestData.selectedApprover = [];
      this.lr.requestData.ishaveedu = 0;
    },
    addLeave() {
      this.initLrData();
      this.$refs.d1.open();
    },
    /*提交请假*/
    saveLeave() {
      this.getUploadFileNames();
      this.lr.requestData.leaveDuration = this.lr.hour * 60 + this.lr.minute;

      if (this.lr.requestData.leaveType == "") {
        this.$messager.alert({
          title: "系统提示",
          icon: "error",
          msg: "请输入假类"
        });
        return;
      }

      if (this.lr.requestData.leaveDuration == 0) {
        this.$messager.alert({
          title: "系统提示",
          icon: "error",
          msg: "请输入请假时长"
        });
        return;
      }

      this.lr.requestData.startDate = dateUtil.format(
        this.lr.dateBegin,
        "YYYY-MM-DD"
      );
      this.lr.requestData.endDate = dateUtil.format(
        this.lr.dateEnd,
        "YYYY-MM-DD"
      );

      this.lr.requestData.firstApprover = 0;
      this.lr.requestData.secondApprover = 0;
      this.lr.requestData.applyType = 1;

      if (this.lr.requestData.remark == "") {
        this.$messager.alert({
          title: "系统提示",
          icon: "error",
          msg: "请假事由不能为空！"
        });
        return;
      }
      this.lr.requestData.startTime =
        this.lr.startTimeHour * 60 + this.lr.startTimeMinute;
      this.lr.requestData.endTime =
        this.lr.endTimeHour * 60 + this.lr.endTimeMinute;

      this.$loading("正在保存中...");
      leave.saveLeave(this.lr.requestData).then(res => {
        this.$loading.close();
        if (res.success) {
          this.$refs.d1.close();
          // this.searching();

          this.$messager.alert({
            title: "系统提示",
            icon: "success",
            msg: "保存成功！"
          });
        } else {
          this.$messager.alert({
            title: "系统提示",
            icon: "error",
            msg: res.result[0].errorMsg
          });
        }
      });
    },
    /*打开批量请假弹窗*/
    openaddLeave() {
      this.initLrData();
      this.$refs.d1.open();
    },
    closeaddLeave() {
      this.$refs.d1.close();
    },
    /*点击添加按钮*/
    lrAddDateData() {
      let _this = this;
      //判断时间不为空并结束日期大于等于开始日期
      if (
        this.lr.requestData.startDate != null &&
        this.lr.requestData.startDate != "" &&
        this.lr.requestData.endDate != null &&
        this.lr.requestData.endDate != ""
      ) {
        if (this.lr.requestData.startDate <= this.lr.requestData.endDate) {
          //假类必须选择
          if (this.lr.requestData.leaveType != "") {
            let daytime = this.lr.hour * 60 + this.lr.minute;
            if (daytime > 0) {
              /*选中的请假类型*/
              let leaveSelectedData = this.lr.leaveData.filter(item => {
                return item.value == this.lr.requestData.leaveType;
              });
              //选中的假类名称
              let leaveNameSelected = leaveSelectedData[0].text;
              let minsj = leaveSelectedData[0].minsj;
              let multiplesj = leaveSelectedData[0].multiplesj;
              let timelimit = leaveSelectedData[0].timelimit;
              if (
                daytime >= minsj &&
                daytime % multiplesj == 0 &&
                daytime <= timelimit
              ) {
                //设置表格中的数字选择框，min  max  步长
                this.lr.minMinute = minsj;
                this.lr.maxMinute = timelimit;
                this.lr.increment = multiplesj;
                // //获取日期集合
                // let dateList = dateUtil.getDateList(
                //   this.lr.requestData.startDate,
                //   this.lr.requestData.endDate
                // );
                // let data = [];
                // for (var i = 0; i < dateList.length; i++) {
                //   let p = {
                //     leaveDate: dateList[i],
                //     leaveMinute: daytime,
                //     leaveName: leaveNameSelected,
                //     leaveId: this.lr.requestData.leaveType,
                //     leaveHourStr: dateUtil.toHourMinute(daytime)
                //   };
                //   data.push(p);
                // }
                // this.lr.requestData.leaveDateData = data;

                // //判断是否需要配置审批人，请假类型是额度假的需要
                // this.lr.requestData.ishaveedu = leaveSelectedData[0].ishaveedu;
                // if (leaveNameSelected == "放班") {
                //   //不需要走审批流，即不需要选择审批人
                //   this.lr.isShowAppr = false;
                // } else {
                //   this.lr.isShowAppr = true;
                // }
              } else {
                this.$messager.alert({
                  title: "系统提示",
                  icon: "warning",
                  msg:
                    "假类:" +
                    leaveNameSelected +
                    ",最小时间:" +
                    minsj +
                    "分钟，最大时间:" +
                    timelimit +
                    "分钟，步长:" +
                    multiplesj +
                    "分钟，您设置的时长为" +
                    daytime +
                    "分钟，不符合条件，请修改。"
                });
              }
            } else {
              this.$messager.alert({
                title: "系统提示",
                icon: "warning",
                msg: "请设置请假时长!"
              });
            }
          } else {
            this.$messager.alert({
              title: "系统提示",
              icon: "warning",
              msg: "请选择假类!"
            });
          }
        } else {
          this.$messager.alert({
            title: "系统提示",
            icon: "warning",
            msg: "开始日期不能晚于结束日期!"
          });
        }
      } else {
        this.$messager.alert({
          title: "系统提示",
          icon: "warning",
          msg: "请配置开始日期和结束日期!"
        });
      }
    },
    deleteDayOfLeave(row, rowIndex) {
      //日请假集合表变更
      this.lr.requestData.leaveDateData.splice(rowIndex, 1);
    },
    onAllCheckedChange(checked) {
      if (this.rowClicked) {
        return;
      }
      this.lr.requestData.peopleData = this.lr.requestData.peopleData.map(
        row => {
          return Object.assign({}, row, {
            selected: checked
          });
        }
      );
    },
    onCheckedChange(checked) {
      this.allChecked =
        this.checkedRows.length === this.lr.requestData.peopleData.length;
      this.rowClicked = true;
      this.$nextTick(() => (this.rowClicked = false));
    },
    /*添加人员*/
    addLeaveUser() {
      let _this = this;
      let tab = this.$refs.leftBar.selectTab;
      let deptIds = null;
      let userIds = null;
      //判断tab的选择是部门还是人员
      if (tab == 1) {
        deptIds = this.$refs.leftBar.getSelectDeptIds();
        if (deptIds == null || deptIds == "") {
          this.$messager.alert({
            title: "系统提示",
            icon: "warning",
            msg: "请勾选要请假的部门!"
          });
          return false;
        }
      } else {
        userIds = this.$refs.leftBar.getSelectUserIds();
        if (userIds == null || userIds == "") {
          this.$messager.alert({
            title: "系统提示",
            icon: "warning",
            msg: "请勾选要请假的人员!"
          });
          return false;
        }
      }
      //整理请求的数据
      let param = {
        deptIds: deptIds,
        userIds: userIds
      };

      // let transferData = this.getTransferData();
      // this.$refs.gridSelect.add(transferData);
      this.$loading("正在获取人员中...");
      user.getUserInfoList(param).then(res => {
        this.$loading.close();
        if (res.code == "200") {
          // let newUser = res.result;
          let userList = _this.getTransferData(res.result);
          console.log("已查到的员工");
          console.log(userList);
          this.$refs.gridSelect.add(userList);
        } else {
          this.$messager.alert({
            title: "异常错误",
            icon: "error",
            msg: "获取数据失败!"
          });
        }
      });
    },
    /**
     * 获取左边树选中的员工
     * @returns {{add: [], update: []}}
     */
    getTransferData(selectUsers) {
      let result = {
        add: [],
        update: []
      };
      //左侧已选择的员工
      // let selectUsers = this.$refs.leftBar.getSelectUsers();
      console.log("左侧已选择的员工");
      console.log(selectUsers);

      //右侧已被选员工
      console.log("右侧已被选员工");
      let gridData = this.$refs.gridSelect.getGridData();
      console.log(gridData);

      selectUsers.forEach(item => {
        if (!item.id) item.id = item.userSerial;
        if (this.checkExist(item, gridData)) {
          result.update.push(item);
        } else {
          result.add.push(item);
        }
      });
      return result;
    },
    /**
     * 检测数组中元素是否存在
     * @param el
     * @param dataList
     */
    checkExist(el, dataList) {
      let filterData = dataList.filter(function(item) {
        return item.userSerial == el.userSerial;
      });
      return filterData && filterData.length > 0;
    },
    /*移除选择的人员*/
    removeLeaveUser() {
      // if (this.allChecked) {
      //   this.lr.requestData.peopleData = [];
      //   this.allChecked = false;
      // } else {
      //   this.lr.requestData.peopleData = this.lr.requestData.peopleData.filter(
      //     row => row.selected != true
      //   );
      // }
      // this.setPeopleTotal();
      this.$refs.gridSelect.removeSelect();
    },
    /*设置人员表格的总条数*/
    setPeopleTotal() {
      this.lr.pageTotalNum = this.lr.requestData.peopleData.length;
    },
    searching() {
      this.parentSearch();
    },
    //整理上传文件名集合
    getUploadFileNames() {
      this.lr.requestData.uploadFileNames = [];
      let upload1 = this.$refs.upload1.getUploadFileName();
      this.addFileNames(upload1);
      let upload2 = this.$refs.upload2.getUploadFileName();
      this.addFileNames(upload2);
      let upload3 = this.$refs.upload3.getUploadFileName();
      this.addFileNames(upload3);
    },
    //添加上传文件名到集合
    addFileNames(name) {
      if (name != null) {
        this.lr.requestData.uploadFileNames.push(name);
      }
    },
    //时间改变，重置时间明细表格数据
    selectionChange(d) {
      //请加日详情表格初始化
      this.lr.requestData.totalDuration = 0;
      this.lr.requestData.leaveDateData = [];
    },
    updateShowStr(rows, column, originalValue) {
      //console.log(rows.row)
      rows.row.leaveHourStr = dateUtil.toHourMinute(rows.row.leaveMinute);
    }
  }
};
</script>

<style scoped>
.dlgContent {
  padding: 10px;
  height: 100%;
  background-color: #efeeed;
  display: flex;
  overflow: hidden;
  /*flex-direction: row;*/
  /*border: 1px solid red;*/
}

.form-fieldset {
  width: 100%;
  border-width: 1px;
  border-style: ridge;
  margin-bottom: 10px;
}

.form-item {
  width: 50%;
  /*border: 1px solid #00B83F;*/
  display: inline-block;
  margin-bottom: 5px;
}

.dlg-foot {
  /*padding: 0 0 20px 0;*/
  /*margin-top: 10px;*/
  text-align: center;
  line-height: 45px;
  height: 45px;
  border-top: 1px solid #d1d5d8;
  /*border: 1px solid red;*/
}

.ag-theme-balham .ag-root-wrapper {
  border: solid 0px;
  border-color: #bdc3c7;
  border-color: #0091ea;
  border-radius: 2px;
}
</style>
